﻿using System;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace JumpstartApp.Controls
{
    public sealed partial class Badge : UserControl
    {
        public Badge()
        {
            this.InitializeComponent();
            Loaded += Badge_Loaded;
        }

        static BitmapImage s_BitmapImage;
        async void Badge_Loaded(object sender, RoutedEventArgs e)
        {
            if (Contracts.Settings.AllowLogin)
            {
                if (Helpers.LiveSdk.User == null)
                {
                    this.NameTextBlock.Text = "Login for more";
                    this.EmailTextBlock.Text = "Click here to try again";
                    this.Tapped += (s, args) => Services.Navigation.GotoSplash();
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                    this.NameTextBlock.Text = Helpers.LiveSdk.User.NameFull;
                    this.EmailTextBlock.Text = Helpers.LiveSdk.User.EmailAccount;

                    try
                    {
                        var _File = await ApplicationData.Current.LocalFolder.GetFileAsync("Badge.png");
                        s_BitmapImage = s_BitmapImage ?? new BitmapImage() { CreateOptions = BitmapCreateOptions.IgnoreImageCache };
                        s_BitmapImage.UriSource = null;
                        s_BitmapImage.UriSource = new Uri(_File.Path);
                        this.BadgeImage.Source = s_BitmapImage;
                    }
                    catch (Exception)
                    {
                        if (Helpers.LiveSdk.User.PhotoBitmap != null)
                            this.BadgeImage.Source = Helpers.LiveSdk.User.PhotoBitmap;
                    }

                    this.Tapped += (s, args) => Services.Navigation.GotoCamera();
                }
            }
            else
            {
                this.Visibility = Visibility.Collapsed;
            }
        }
    }
}
